package com.ecactus.androidappframework.mvvm2.model;

import android.database.Cursor;

import com.ecactus.androidappframework.mvvm2.utils.DbUtils;
import com.ecactus.androidappframework.mvvm2.utils.HttpUtils;
import com.google.gson.Gson;

import java.util.LinkedList;
import java.util.List;

public class UserBusiness {
    private static final UserBusiness INSTANCE = new UserBusiness();

    private List<UserListener> mListeners = new LinkedList<>();

    public static UserBusiness get() {
        return INSTANCE;
    }

    public void addListener(UserListener listener) {
        if(listener == null) {
            return;
        }
        synchronized (mListeners) {
            if(!mListeners.contains(listener)) {
                mListeners.add(listener);
            }
        }
    }

    public void removeListener(UserListener listener) {
        if(listener == null) {
            return;
        }
        synchronized (mListeners) {
            mListeners.remove(listener);
        }
    }

    public User getUser() {
        Cursor cursor = DbUtils.query(null);
        if(cursor != null) {
            try {

            } catch (Exception e) {

            } finally {
                cursor.close();
            }
        }
        User user = new User();
        user.name = "小虾米";
        user.age = 21;
        return user;
    }

    public void requestUser() {
        HttpUtils.request(null, new HttpUtils.ResponseCallback() {
            @Override
            public void onResponseSuccessed(String json) {
                User user = null;
                try {
                    user = new Gson().fromJson(json, User.class);
                } catch (Exception e) {
                }
                if(user != null) {
                    String updateSql = null;
                    DbUtils.update(updateSql);
                    notifyRequestUser(0, user);
                } else {
                    notifyRequestUser(1, null);
                }
            }

            @Override
            public void onResponseFailed(int reason) {
                notifyRequestUser(reason, null);
            }
        });
    }

    private void notifyRequestUser(int code, User user) {
        List<UserListener> listeners = new LinkedList<>();
        synchronized (mListeners) {
            listeners.addAll(mListeners);
        }
        for(UserListener listener : listeners) {
            listener.onRequestUserResult(code, user);
        }
    }

    public interface UserListener {
        void onRequestUserResult(int code, User user);
    }
}
